package com.softcits.hw.service;

import java.util.Collections;
import java.util.List;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.softcits.hw.model.MailInfo;

@Service
public class EmailService {

    @Value("${mail.ServerHost}")
    private String serverHost;

    @Value("${mail.SenderAddress}")
    private String senderAddress;

    @Value("${mail.SenderNick}")
    private String senderNick;

    @Value("${mail.SenderUsername}")
    private String senderUsername;

    @Value("${mail.SenderPassword}")
    private String senderPassword;

    public boolean sendEmail(MailInfo info) throws EmailException {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(this.serverHost);
        email.setFrom(senderAddress, senderNick);
        email.setAuthentication(senderUsername, senderPassword);
        email.setCharset("UTF-8");
        
        
        email.setSubject(info.getSubject());
        email.setTextMsg(info.getContent());
        
        List<String> toList = info.getToAddress();
        if(toList == null || toList.isEmpty()) {
            throw new EmailException("Please specify Target Email Addresses ");
        }
        
        for(String add : toList) {
            email.addTo(add);
        }
        
        List<String> ccList = info.getCcAddress();
        if(ccList != null) {
            for(String cc: ccList) {
                email.addCc(cc);
            }
        }
        
        List<String> bccList = info.getBccAddress();
        if(ccList != null) {
            for(String bcc: bccList) {
                email.addBcc(bcc);
            }
        }
       
        // TODO attachement
        
        email.send();
        
        return true;
    }
}
